package com.future.interview;

/**
 * Description: 面试题 01.06. 字符串压缩
 *
 * @author weiruibai.vendor
 * Date: 2022/11/10 10:41
 */
public class Solution_0106 {

    static Solution_0106 instance = new Solution_0106();

    public static void main(String[] args) {
        String s = "aabcccccaaa";
        s = "abbccd";
        s = "aabcccccaa";
        System.out.println(instance.compressString(s));
    }

    public String compressString(String S) {
        if (S == null || S.length() < 2) {
            return S;
        }
        int N = S.length();
        char[] chars = S.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < N; ) {
            sb.append(chars[i]);
            int count = 1;
            int j = i + 1;
            while (j < N && chars[i] == chars[j]) {
                count++;
                j++;
            }
            i = j;
            sb.append(count);
        }
        if (sb.toString().length() >= S.length()) {
            return S;
        } else {
            return sb.toString();
        }
    }
}
